<template>
  <div class="home-container">
    <!-- 顶部导航 -->
  <div class="header">
    <div class="header-inner">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="鲸选Logo" />
      </div>
      <div class="search-bar" @click.stop>
        <input v-model="searchQuery" type="text" placeholder="输入商品" @focus="showHistory = true"
          @keypress.enter="handleSearch" />
        <div v-show="showHistory" class="search-history-dropdown">
          <template v-if="searchHistory.length > 0">
            <div v-for="(term, i) in searchHistory" :key="i" class="search-history-item" @click="selectHistory(term)">
              {{ term }}
            </div>
            <div class="search-history-item clear-history" @click="clearHistory">
              🗑️ 清空历史记录
            </div>
          </template>
          <div v-else class="search-history-item no-record">
            暂无搜索记录
          </div>
        </div>
        <button @click="handleSearch">搜索</button>
      </div>
      <div class="header-right">
        <button class="btn" @click="goToHomePage">返回主页</button>
        <div class="user-menu" @click.stop>
          <div class="user-avatar">
            <img :src="userAvatar" alt="用户头像" />
          </div>
          <div>
            <span class="username" @click="toggleUserMenu">{{ displayName }}</span>
            <div v-show="isUserMenuOpen" class="user-dropdown">
              <div v-for="(item, index) in userMenuItems" :key="index" class="dropdown-item"
                @click="handleMenuClick(item)">
                {{ item.text }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 筛选滑块区域 -->
  <div class="filter-panel">
    <div v-for="(row, rowIndex) in filterRows" :key="rowIndex" class="filter-row">
      <div v-for="(item, colIndex) in row" :key="colIndex" class="filter-item">
        <div class="filter-label">{{ item.label }}</div>
        <div class="slider-container">
          <div class="slider" @click="handleSliderClick($event, rowIndex, colIndex)">
            <div class="slider-track"></div>
            <div class="slider-progress" :style="{ width: `${item.progress}%` }"></div>
            <div class="slider-thumb" :style="{ left: `${item.progress}%` }"
              @mousedown="startDrag($event, rowIndex, colIndex)"></div>
          </div>
          <div class="value-controls">
            <button class="value-btn" @click="decrementValue(rowIndex, colIndex)">−</button>
            <input type="text" class="value-input" :value="Math.round(item.value)"
              @change="updateValueFromInput($event, rowIndex, colIndex)" />
            <button class="value-btn" @click="incrementValue(rowIndex, colIndex)">+</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 商品列表 -->
  <div class="product-list">
    <div v-if="loading" class="product-loading">正在搜索，请稍候...</div>
    <div v-else-if="error" class="product-error">{{ error }}</div>
    <div v-else-if="products.length === 0" class="product-empty">暂无匹配的商品，请尝试其他关键词</div>
    <template v-else>
      <div v-for="(product, index) in products" :key="product.productId || index" class="product-card">
        <div class="product-image">
          <img :src="product.imageUrl || placeholderImage" :alt="product.productName || '商品图片'" />
        </div>
        <div class="product-info">
          <div class="product-title">{{ product.productName || '商品' }}</div>
          <div class="product-price">{{ formatPrice(product.price) }}</div>
          <div class="product-desc">{{ product.platformName || '平台信息待补充' }}</div>
          <!-- 显示相关性得分 -->
          <div v-if="product.relevanceScore != null" class="relevance-indicator">
            <span class="relevance-label">匹配度：</span>
            <div class="relevance-bar">
              <div class="relevance-fill" :style="{ width: `${Math.min(product.relevanceScore, 100)}%` }"></div>
            </div>
            <span class="relevance-score">{{ product.relevanceScore }}%</span>
          </div>
        </div>
        <div class="product-actions">
          <button class="action-btn primary" @click="handleViewProduct(product, index)">查看详情</button>
          <button class="action-btn" @click="addToCart(product)">加入购物车</button>
        </div>
      </div>
    </template>
  </div>
  </div>

</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { searchProducts, searchProductsWithWeights, recordBrowseBehavior, recordSearchBehavior, logout as logoutApi } from '@/api'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// ========== 用户菜单 ==========
const isUserMenuOpen = ref(false)
const userMenuItems = [
  { text: '购物车', to: '/shopping-cart' },
  { text: '个人中心', to: '/personalcenter' },
  { text: '切换账号', to: '/user-login' },
  { text: '修改密码', to: '/change-password' },
  { text: '退出登录', to: '/user-login' }
]
const defaultAvatar = new URL('@/assets/user-01.svg', import.meta.url).href
const userAvatar = computed(() => userStore.info?.icon || defaultAvatar)
const displayName = computed(() => userStore.userName || '未登录')

const toggleUserMenu = () => {
  isUserMenuOpen.value = !isUserMenuOpen.value
}

const handleMenuClick = async (item) => {
  isUserMenuOpen.value = false
  if (item.text === '退出登录') {
    if (confirm('确定要退出登录吗？')) {
      try {
        await logoutApi()
      } catch (error) {
        console.warn('退出登录接口调用失败:', error)
      }
      userStore.clearAuth()
      router.push('/user-login')
    }
    return
  }

  if (item.text === '切换账号') {
    userStore.clearAuth()
    router.push('/user-login')
    return
  }

  if (item.to) {
    router.push(item.to)
  }
}

// ========== 全局点击处理 ==========
const handleClickOutside = (e) => {
  if (!e.target.closest('.user-menu')) {
    isUserMenuOpen.value = false
  }
  if (!e.target.closest('.search-bar')) {
    showHistory.value = false
  }
}

// ========== 搜索历史 ==========
const searchQuery = ref(route.query.q ? String(route.query.q) : '')
const showHistory = ref(false)
const searchHistory = ref([])

const loadHistory = () => {
  try {
    const history = JSON.parse(localStorage.getItem('searchHistory') || '[]')
    searchHistory.value = Array.isArray(history) ? history : []
  } catch (error) {
    console.warn('解析搜索历史失败，已清空', error)
    searchHistory.value = []
    localStorage.removeItem('searchHistory')
  }
}

const saveHistory = (term) => {
  const cleanTerm = term.trim()
  if (!cleanTerm) return
  const history = [cleanTerm, ...searchHistory.value.filter((t) => t !== cleanTerm)].slice(0, 10)
  localStorage.setItem('searchHistory', JSON.stringify(history))
  searchHistory.value = history
}

const clearHistory = () => {
  localStorage.removeItem('searchHistory')
  searchHistory.value = []
  searchQuery.value = ''
}

const selectHistory = (term) => {
  const cleanTerm = term.trim()
  if (!cleanTerm) return
  searchQuery.value = cleanTerm
  saveHistory(cleanTerm)
  showHistory.value = false
  router.push({ path: '/search', query: { q: cleanTerm } })
}

const handleSearch = () => {
  const query = searchQuery.value.trim()
  if (!query) return
  saveHistory(query)
  showHistory.value = false
  router.push({ path: '/search', query: { q: query } })
}

// ========== 返回主页 ==========
const goToHomePage = () => {
  router.push('/home')
}

// ========== 滑块逻辑 ==========
const MAX_VAL = 100

const filterRows = ref([
  [
    { label: '价格', value: 0, progress: 0 },
    { label: '口碑', value: 0, progress: 0 }
  ],
  [
    { label: '热度', value: 0, progress: 0 },
    { label: '时效', value: 0, progress: 0 }
  ]
])

// 系统默认权重
const defaultWeights = {
  price: 25,
  reputation: 35,
  heat: 25,
  timeliness: 15
}

const updateSlider = (row, col, val) => {
  const clamped = Math.max(0, Math.min(MAX_VAL, val))
  const percent = (clamped / MAX_VAL) * 100
  filterRows.value[row][col].value = clamped
  filterRows.value[row][col].progress = percent
  
  // 添加调试日志
  console.log('滑块值已更新:', {
    row, col, value: clamped, percent,
    weights: {
      price: filterRows.value[0][0].value,
      reputation: filterRows.value[0][1].value,
      heat: filterRows.value[1][0].value,
      timeliness: filterRows.value[1][1].value
    }
  })
  
  // 当滑块值改变时，自动重新搜索
  if (currentKeyword.value) {
    // 添加延迟，避免频繁请求
    setTimeout(() => {
      fetchProducts(currentKeyword.value)
    }, 500)
  }
}

const decrementValue = (row, col) => {
  updateSlider(row, col, filterRows.value[row][col].value - 1)
}

const incrementValue = (row, col) => {
  updateSlider(row, col, filterRows.value[row][col].value + 1)
}

const updateValueFromInput = (e, row, col) => {
  const val = parseFloat(e.target.value) || 0
  updateSlider(row, col, val)
}

const handleSliderClick = (e, row, col) => {
  const slider = e.currentTarget
  const rect = slider.getBoundingClientRect()
  const offsetX = e.clientX - rect.left
  const percent = (offsetX / rect.width) * 100
  const val = (percent / 100) * MAX_VAL
  updateSlider(row, col, val)
}

let dragInfo = null
const startDrag = (e, row, col) => {
  e.preventDefault()
  const slider = e.currentTarget.parentElement
  const rect = slider.getBoundingClientRect()
  const startX = e.clientX
  const startVal = filterRows.value[row][col].value

  const move = (moveEvent) => {
    const deltaX = moveEvent.clientX - startX
    const newVal = startVal + (deltaX / rect.width) * MAX_VAL
    updateSlider(row, col, newVal)
  }

  const stop = () => {
    document.removeEventListener('mousemove', move)
    document.removeEventListener('mouseup', stop)
    dragInfo = null
  }

  dragInfo = { move, stop }
  document.addEventListener('mousemove', move)
  document.addEventListener('mouseup', stop)
}

// ========== 商品数据 ==========
const products = ref([])
const loading = ref(false)
const error = ref('')
const placeholderImage = 'https://via.placeholder.com/150?text=商品图片'

const formatDateTime = (date = new Date()) => {
  const d = new Date(date)
  const pad = (value) => String(value).padStart(2, '0')
  // 获取时区偏移量（分钟），转换为小时和分钟
  const offset = -d.getTimezoneOffset() // getTimezoneOffset 返回的是 UTC 与本地时间的差值（分钟）
  const offsetHours = Math.floor(Math.abs(offset) / 60)
  const offsetMinutes = Math.abs(offset) % 60
  const offsetSign = offset >= 0 ? '+' : '-'
  const offsetStr = `${offsetSign}${pad(offsetHours)}:${pad(offsetMinutes)}`
  // 返回 ISO 8601 格式，包含时区信息
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}${offsetStr}`
}
const toNumber = (value) => {
  const num = Number(value)
  return Number.isFinite(num) ? num : undefined
}

const formatPrice = (value) => {
  const num = Number(value)
  if (Number.isFinite(num)) {
    return `¥${num.toFixed(2)}`
  }
  if (value !== null && value !== undefined && value !== '') {
    return `¥${value}`
  }
  return '¥0.00'
}

const fetchProducts = async (keyword) => {
  const cleanKeyword = (keyword || '').trim()
  if (!cleanKeyword) {
    products.value = []
    return
  }
  loading.value = true
  error.value = ''
  try {
    // 获取用户设置的权重
    const userPriceWeight = filterRows.value[0][0].value
    const userReputationWeight = filterRows.value[0][1].value
    const userHeatWeight = filterRows.value[1][0].value
    const userTimelinessWeight = filterRows.value[1][1].value
    
    // 计算用户是否调整过权重（所有值都为0表示未调整）
    const hasUserAdjustment = userPriceWeight > 0 || userReputationWeight > 0 ||
                           userHeatWeight > 0 || userTimelinessWeight > 0
    
    let finalWeights
    if (hasUserAdjustment) {
      // 用户调整过，根据滑块值的占比计算权重
      const totalUserWeight = userPriceWeight + userReputationWeight + userHeatWeight + userTimelinessWeight
      
      if (totalUserWeight > 0) {
        // 计算每个维度的占比，然后应用到默认权重上
        const priceRatio = userPriceWeight / totalUserWeight
        const reputationRatio = userReputationWeight / totalUserWeight
        const heatRatio = userHeatWeight / totalUserWeight
        const timelinessRatio = userTimelinessWeight / totalUserWeight
        
        // 基于占比调整默认权重
        finalWeights = {
          price: defaultWeights.price * (1 + priceRatio),
          reputation: defaultWeights.reputation * (1 + reputationRatio),
          heat: defaultWeights.heat * (1 + heatRatio),
          timeliness: defaultWeights.timeliness * (1 + timelinessRatio)
        }
      } else {
        finalWeights = defaultWeights
      }
    } else {
      // 用户未调整，使用默认权重
      finalWeights = defaultWeights
    }
    
    console.log('权重计算:', {
      hasUserAdjustment,
      userWeights: { price: userPriceWeight, reputation: userReputationWeight, heat: userHeatWeight, timeliness: userTimelinessWeight },
      finalWeights
    })
    
    // 使用带权重的搜索接口
    const response = await searchProductsWithWeights({
      keyword: cleanKeyword,
      priceWeight: finalWeights.price,
      reputationWeight: finalWeights.reputation,
      heatWeight: finalWeights.heat,
      timelinessWeight: finalWeights.timeliness,
      page: 1,
      pageSize: 20
    })
    
    const list = Array.isArray(response?.data?.products) ? response.data.products : []
    products.value = list
    
    if (userStore.isLoggedIn) {
      await recordSearchBehavior({
        userId: userStore.userId,
        keyword: cleanKeyword,
        timestamp: formatDateTime(),
        clicked: false,
        // 记录用户使用的权重配置
        weightConfig: {
          priceWeight: finalWeights.price,
          reputationWeight: finalWeights.reputation,
          heatWeight: finalWeights.heat,
          timelinessWeight: finalWeights.timeliness
        }
      })
    }
  } catch (err) {
    console.error('搜索商品失败:', err)
    // 如果权重搜索失败，回退到普通搜索
    try {
      const fallbackResponse = await searchProducts({ keyword: cleanKeyword, page: 1, pageSize: 20 })
      const list = Array.isArray(fallbackResponse?.data?.products) ? fallbackResponse.data.products : []
      products.value = list
      
      if (userStore.isLoggedIn) {
        await recordSearchBehavior({
          userId: userStore.userId,
          keyword: cleanKeyword,
          timestamp: formatDateTime(),
          clicked: false
        })
      }
    } catch (fallbackErr) {
      console.error('降级搜索也失败:', fallbackErr)
      error.value = fallbackErr?.message || '搜索商品失败，请稍后重试'
      products.value = []
    }
  } finally {
    loading.value = false
  }
}

const currentKeyword = computed(() => (route.query.q ? String(route.query.q) : ''))

watch(
  () => route.query.q,
  (newKeyword) => {
    searchQuery.value = newKeyword ? String(newKeyword) : ''
    fetchProducts(currentKeyword.value)
  },
  { immediate: true }
)

const handleViewProduct = async (product, index) => {
  const productId = product?.productId?.toString()
  if (!productId) {
    alert('商品信息缺失，无法查看详情')
    return
  }

  if (userStore.isLoggedIn) {
    try {
      const now = new Date()
      const keyword = currentKeyword.value?.trim()
      if (keyword) {
        try {
          await recordSearchBehavior({
            userId: userStore.userId,
            keyword,
            timestamp: formatDateTime(),
            clicked: true,
            clickedProductId: Number(productId),
            clickRank: typeof index === 'number' ? Math.max(index, 0) : 0
          })
        } catch (error) {
          console.warn('记录搜索点击失败:', error)
        }
      }

      const payload = {
        userId: userStore.userId,
        productId: Number(productId),
        startTime: formatDateTime(new Date(now.getTime() - 2000)),
        endTime: formatDateTime(now),
        pageDepth: 1,
        pageCount: 1
      }
      const price = toNumber(product.price)
      if (price !== undefined) {
        payload.price = price
      }
      if (product.platformName) {
        payload.category = product.platformName
      }
      await recordBrowseBehavior(payload)
    } catch (error) {
      console.warn('记录浏览行为失败:', error)
    }
  }

  router.push({ path: `/iteminfo/${productId}` })
}

const addToCart = async (product) => {
  const productId = product.productId?.toString() ?? ''
  if (!productId) {
    alert('商品信息缺失，无法加入购物车')
    return
  }

  const success = await cartStore.addItem(productId, 1)
  if (success) {
    alert('已加入购物车')
  } else if (cartStore.error) {
    alert(`加入购物车失败：${cartStore.error}`)
  } else {
    alert('加入购物车失败，请稍后重试')
  }
}

// ========== 生命周期 ==========
onMounted(() => {
  loadHistory()
  document.addEventListener('click', handleClickOutside)
})
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
  if (dragInfo) {
    document.removeEventListener('mousemove', dragInfo.move)
    document.removeEventListener('mouseup', dragInfo.stop)
  }
})
</script>

<style>
body {
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  min-height: 100vh;
}
</style>

<style scoped>
@import '@/CSS/SearchResult.css';
</style>
